package com.iwayin.core.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * 
 * @author xiaobo.feng<xiaobo.feng@foxmail.com>
 * 
 *         Sep 9, 2011
 */
public class URLReplaceUtil {

	private static String DEFAUT_DOMAIN = "http://freebao.com/";
	// private static String rex = "http://[\\w\\.\\-/:]+";
	private static String rex = "http(s)?://([\\w-]+\\.?)+[\\w-]+(/[\\w- ./?%&=]*)?";

	public static String urlReplaceAll(String str, String replace) {
		boolean flag = true;
		StringBuilder sb = new StringBuilder();
		while (flag) {
			String newU = urlReplaceFirst(str, null);
			int from = newU.indexOf("</a>", 0);
			if (from > -1) {
				sb.append(newU.substring(0, from + 4));
				str = newU.substring(from + 4);
			} else {
				sb.append(newU);
				flag = false;
			}
		}
		return sb.toString();
	}

	public static String urlReplaceFirst(String str, String replace) {
		String returnStr = "";
		Pattern p = Pattern.compile(rex);
		Matcher matcher = p.matcher(str);
		if (matcher.find()) {
			String u = matcher.group();
			StringBuilder sb = new StringBuilder();
			if (StringUtil.isNotBlank(replace))
				DEFAUT_DOMAIN = replace;
			sb.append("<a target='blank' href='").append(u).append("' title='").append(u).append("'>").append(DEFAUT_DOMAIN)
					.append(MDEncryption.encodeMD5(u).subSequence(0, 8)).append("</a>");
			returnStr = str.replaceFirst(rex, sb.toString());
			return returnStr;
		} else {
			return str;
		}
	}

	public static String url(String url) {
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		StringBuffer resultSb = new StringBuffer();
		try {
			client.executeMethod(method);
			if (200 == method.getStatusCode()) {
				String desRex = "(?i)<meta name=\"description\" content=\".*\"";
				String titleRex = "(?i)<title>.*</title>";

				String response = method.getResponseBodyAsString();
				@SuppressWarnings("deprecation")
				String favicon = "http://" + method.getHostConfiguration().getHost() + "/favicon.ico";

				String des = URLReplaceUtil.rexMatch(response, desRex);
				des = des.substring(34, des.length() - 1);

				String title = URLReplaceUtil.rexMatch(response, titleRex);
				int end = title.length() - 8;
				if (title.indexOf("_") > 0) {
					end = title.indexOf("_");
				}
				title = title.substring(7, end);
				resultSb.append("<h3><a href="+url+"><img src=\"").append(favicon).append("\" />").append(title).append("</a></h3><p>").append(des).append("</p>");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//连接释放
			method.releaseConnection();
		}
		return resultSb.toString();
	}

	public static String rexMatch(String str, String match) {
		Pattern p = Pattern.compile(match);
		Matcher m = p.matcher(str);
		while (m.find()) {
			return m.group();
		}
		return null;
	}
	
}
